<template>
  <div>
    <el-card shadow="never">
      <el-form label-width="auto" :inline="true" size="small">
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同编号" style="width: 85%">
              <el-input
                v-model="searchForm.contractNo"
                placeholder="请输入 合同编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同名称" style="width: 85%">
              <el-select
                v-model="searchForm.contractName"
                clearable
                filterable
                remote
                remote-show-suffix
                placeholder="请选择 合同名称"
                :remote-method="getContractNameList"
                size="small"
              >
                <el-option
                  v-for="item in contractOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  class="!w-[500px]"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称" style="width: 85%">
              <el-select
                v-model="searchForm.projectName"
                clearable
                filterable
                remote
                remote-show-suffix
                placeholder="请选择 项目名称"
                :remote-method="getProjectNameList"
                size="small"
              >
                <el-option
                  v-for="item in projectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  class="!w-[500px]"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同状态" style="width: 85%">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择 合同状态"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in contractStatusOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="回款日期" style="width: 85%">
              <el-date-picker
                v-model="searchForm.date"
                type="daterange"
                range-separator="-"
                start-placeholder="开始"
                end-placeholder="结束"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button
              color="#1E3485"
              size="small"
              :icon="Search"
              @click="getList()"
              >搜索</el-button
            >
            <el-button
              type="default"
              size="small"
              :icon="Delete"
              @click="clearAllFields()"
              >清空</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <vxe-table
        border
        min-height="300"
        max-height="650"
        header-align="center"
        :column-config="{ resizable: true }"
        :row-config="{ isHover: true }"
        :data="tableData"
        size="mini"
        :pager-config="tablePage"
        style="margin-top: 1%"
        :cell-style="cellStyle"
      >
        <!-- <vxe-column
          type="seq"
          title="序号"
          width="50"
          fixed="left"
          align="center"
        /> -->
        <vxe-column
          v-for="column in tableColumns"
          :key="column.field"
          header-align="center"
          :field="column.field"
          :title="column.title"
          :min-width="column.width"
          :align="column.align"
          :fixed="column.fixed"
          show-overflow
        >
          <template
            v-if="column.field === 'contractMethod'"
            v-slot:default="{ row }"
          >
            <span v-if="row.contractMethod === '0'">锁定</span>
            <span v-if="row.contractMethod === '1'">浮动</span>
          </template>
          <template
            v-else-if="column.field === 'status'"
            v-slot:default="{ row }"
          >
            <span v-if="row.status === 1">待回款</span>
            <!-- <span v-if="row.status === 2">审核中</span>
            <span v-if="row.status === 3">撤回</span>
            <span v-if="row.status === 4">审核驳回</span>
            <span v-if="row.status === 5">待项目确认</span>
            <span v-if="row.status === 6">项目确认驳回</span>
            <span v-if="row.status === 7">待回款</span>
            <span v-if="row.status === 8">回款中</span> -->
            <span v-if="row.status === 9">回款完成</span>
            <!-- <span v-if="row.status === 10">回款延迟</span> -->
          </template>
          <!-- <template
            v-else-if="column.field === 'receiptStatus'"
            v-slot:default="{ row }"
          >
            <span v-if="row.auditStatus === '0'">待申请</span>
            <span v-if="row.auditStatus === '1'">已申请</span>
            <span v-if="row.auditStatus === '2'">已留存</span>
          </template> -->
          <template
            v-else-if="column.field === 'contractPrePaymentRate'"
            v-slot:default="{ row }"
          >
            <span>{{ row.contractPrePaymentRate + "%" }}</span>
          </template>
          <template
            v-else-if="column.title == '未付款金额（元）'"
            v-slot:default="{ row }"
          >
            <span>{{
              (
                Number(row.contractPrePaymentPrice) - Number(row.receivePrice)
              ).toFixed(2)
            }}</span>
          </template>
        </vxe-column>
        <vxe-column title="操作" min-width="200" align="center" fixed="right">
          <template v-slot:default="{ row }">
            <vxe-button
              type="text"
              @click="toDetail({ id: row.id, action: 'view' }, 'viewPCAP')"
              >查看</vxe-button
            >
            <!-- <vxe-button type="text" disabled>
              <span
                v-if="row.status == 1 || row.status == 4 || row.status == 6"
              >
                提交审批
              </span>
              <span v-if="row.status == 2"> 审核 </span>
              <span v-if="row.status == 5"> 项目部确认 </span>
            </vxe-button>
            <vxe-button
              v-if="row.auditStatus === '0'"
              type="text"
              @click="showReceiptDialog(row)"
              >收据</vxe-button
            > -->
            <vxe-button v-if="row.status != 9" type="text" @click="gourl()"
              >去付款</vxe-button
            >
            <!-- <vxe-button
              v-if="row.status == 0"
              type="text"
              @click="completed(row)"
            >
              付款完成</vxe-button
            > -->
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager
        v-model:current-page="tablePage.currentPage"
        v-model:page-size="tablePage.pageSize"
        :layouts="[
          'Sizes',
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'FullJump',
          'Total'
        ]"
        :total="tablePage.total"
        size="mini"
        style="margin-top: 2%"
        @page-change="handlePageChange"
      />
      <div class="dialogs">
        <el-dialog
          v-model="CollectiondialogVisible"
          title="付款完成"
          width="500"
        >
          <el-form :model="form">
            <el-form-item label="完成付款说明:" label-position="top">
              <el-input
                v-model="checkMark"
                autocomplete="off"
                :rows="3"
                type="textarea"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="Paymentandreceiptcompleted">
                确认
              </el-button>
              <el-button @click="CollectiondialogVisible = false"
                >取消</el-button
              >
            </div>
          </template>
        </el-dialog>
        <receiptDialog
          :visible="receiptDialogVisible"
          :date="date"
          @close="closeReceiptDialog"
        />
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { Delete, Search, Edit } from "@element-plus/icons-vue";
import { VxePagerEvents } from "vxe-table";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDetail } from "@/views/ERP_PaymentMange/ERP_CollectInAdvance/ERP_PurchaseContractAdvancePayment/components/utils/hooks";

import receiptDialog from "./components/dialog/receiptDialog.vue";
import { useRouter } from "vue-router";
import {
  getcontractpaymentpageList,
  getcontractpaymentfinishPayment
} from "@/api/ERP_PaymentMange";
import { getProjectList } from "@/api/ERP_public";
import { getSalesContractsList } from "@/api/ERP_sales";
// 路由跳转
const route = useRouter();
const { toDetail, router } = useDetail();
let searchForm = reactive({
  contractNo: "",
  contractName: "",
  projectName: "",
  status: "",
  date: []
});
let form = reactive({
  Collectiondescribe: ""
});

// 合同状态字典
let contractStatusOptions = ref([
  { key: "1", label: "待回款", value: "1" },
  // { key: "2", label: "审核中", value: "2" },
  // { key: "3", label: "撤回", value: "3" },
  // { key: "4", label: "审核驳回", value: "4" },
  // { key: "5", label: "待项目确认", value: "5" },
  // { key: "6", label: "项目确认驳回", value: "6" },
  // { key: "7", label: "待回款", value: "7" },
  // { key: "8", label: "回款中", value: "8" },
  { key: "9", label: "回款完成", value: "9" }
  //{ key: "10", label: "回款延迟", value: "10" }
]);

onMounted(async () => {
  getList();
});

// ---------------------- 数据请求 --------------------------
// 获取列表
async function getList() {
  let params: any = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  if (searchForm.contractNo != "") {
    params.contractNo = searchForm.contractNo;
  }
  if (searchForm.contractName != "") {
    params.contractName = searchForm.contractName;
  }
  params.contractType = "1";
  if (searchForm.projectName != "") {
    params.projectName = searchForm.projectName;
  }
  if (searchForm.status != "") {
    params.status = searchForm.status;
  }
  if (searchForm.date && searchForm.date?.length != 0) {
    params.beginDate = searchForm.date[0];
    params.endDate = searchForm.date[1];
  }
  getcontractpaymentpageList(params).then((response: any) => {
    tableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  });
}

// ---------------------- 数据展示 --------------------------
// 表格数据
let tableData = ref();
const tableColumns = ref([
  {
    field: "contractNo",
    title: "合同编号",
    width: 150,
    align: "left",
    fixed: "left"
  },
  {
    field: "contractName",
    title: "合同名称",
    width: 200,
    align: "left",
    fixed: "left"
  },
  {
    field: "projectName",
    title: "项目名称",
    width: 200,
    align: "left"
  },
  {
    field: "contractTotalPrice",
    title: "合同总额(元)",
    width: 120,
    align: "center"
  },
  {
    field: "contractMethod",
    title: "合同类型",
    width: 120,
    align: "center"
  },
  {
    field: "status",
    title: "状态",
    width: 120,
    align: "center"
  },
  // {
  //   field: "receiptStatus",
  //   title: "收据",
  //   width: 120,
  //   align: "center"
  // },
  {
    field: "supplierDeptName",
    title: "生产厂家（供应商）",
    width: 200,
    align: "left"
  },
  {
    field: "contractPrePaymentRate",
    title: "预付款比例",
    width: 120,
    align: "center"
  },
  {
    field: "contractPrePaymentPrice",
    title: "预付款金额（元）",
    width: 120,
    align: "center"
  },
  {
    field: "",
    title: "未付款金额（元）",
    width: 120,
    align: "center"
  },
  {
    field: "contractPrePaymentDate",
    title: "预付款截至日期",
    width: 120,
    align: "center"
  }
]);

const checkMark = ref();

// 清空按钮点击事件
const clearAllFields = () => {
  for (const key in searchForm) {
    if (searchForm.hasOwnProperty(key)) {
      if (key === "invoicingDate") {
        searchForm[key] = [];
      } else {
        searchForm[key] = "";
      }
    }
  }
};
// 表格分页配置
let tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};

//单元格样式
const cellStyle = ({ row, column }) => {
  if (column.field === "contractPrePaymentPrice") {
    return {
      color: "red"
    };
  }
  if (column.field === "contractPrePaymentDate") {
    return {
      color: "red"
    };
  }
};

//窗体
const CollectiondialogVisible = ref(false);
// 收据管理弹窗
let receiptDialogVisible = ref(false);
let date = ref();
function showReceiptDialog(row) {
  date.value = row;
  receiptDialogVisible.value = true;
}
function closeReceiptDialog(val: boolean) {
  receiptDialogVisible.value = val;
  getList();
}

const paymentId = ref();
function completed(row) {
  CollectiondialogVisible.value = true;
  paymentId.value = row.id;
}
function Paymentandreceiptcompleted() {
  let params: any = {};
  params.paymentId = paymentId.value;
  params.contractType = "1";
  params.checkMark = checkMark.value;
  getcontractpaymentfinishPayment(params).then((response: any) => {
    if (response.code === 200) {
      CollectiondialogVisible.value = false;
      getList();
    }
  });
}
function gourl() {
  route.push({ path: "/ERP_PaymentMange/ERP_PaymentMange/PaymentMange" });
}
// 合同名称选择
let contractOptions = ref([]);
// 合同名称列表下拉框
const getContractNameList = (query: string) => {
  getSalesContractsList({
    pageIndex: 1,
    pageSize: 10,
    contractType: "0",
    contractName: query
  }).then(response => {
    contractOptions.value = (response as any).data.records.map(item => ({
      label: item.contractName,
      value: item.contractName
    }));
  });
  if (query) {
    setTimeout(() => {
      getSalesContractsList;
    }, 1500);
  }
};
// 项目名称选择
let projectOptions = ref([]);
// 项目名称列表下拉框
const getProjectNameList = (query: string) => {
  getProjectList({
    pageIndex: 1,
    pageSize: 10,
    projectName: query
  }).then(response => {
    projectOptions.value = (response as any).data.records.map(item => ({
      label: item.projectName,
      value: item.projectName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProjectList;
    }, 1500);
  }
};
</script>
<style lang="scss" scoped></style>
